// pages/shoppingMallMini/shoppingMallMini.js
const app = getApp();
const poster = require("../../public/common/poster")
Page({

  /**
   * 页面的初始数据
   */
  data: app.globalData.extend(poster,{
    Url:app.globalData.Url
  },{
    /*  */
    options:{},
    /* 用户信息 */
    userInfo_share:{},
    /* 产品详情数据 */
    productInfo:{
      info:{
        isPay:"0"
      }
    },
    /*  */
    item_id:"",  //产品Id
    item_basic_info:{},  //从产品页传过来的信息
    item_real_info:{},  //请求详情接口获取的信息
    /*  */
    imageData:[  //图片数据
      
    ],
    /*  */
    pro_url:'',
    /*  */
    sharePop:false
  }),
  /* 海报保存到本地 */
  savePosterToLocal: function () {
    return app.globalData.saveCanvasImg.call(this,this.data.posterImgSrc).then(()=>{
      this.setData({
        showPosterPop:true
      })
    })
  },
  /* 生成海报 */
  createPoster(){
    //
    wx.showLoading({
      title:"生成海报",
      mask:true
    });
    //清空画布
    app.globalData.clearCanvas.call(this);
    //计算边距
    const edgeSize = this.data.calcEdgesize.call(this,app.globalData.windowWidth);
    console.log(this.data.contentWid);
    this.setData({
      edgeSize: edgeSize,
      initX:edgeSize,
      initY:edgeSize
    });
    //绘制产品图
    this.data.paintImg.call(this,this.data.imageData[0].image,this.data.initX,this.data.initY,true)
    .then(info=>{
      let x = this.data.initX;
      //let y = this.data.transferSize(info.h) + this.data.transferSize(52);
      let y = info.h + this.data.transferSize(52);
      let x1 = this.data.transferSize(212) + this.data.initX*3;
      //let y1 = this.data.transferSize(info.h) - this.data.edgeSize + this.data.transferSize(52);
      let y1 = info.h - this.data.edgeSize + this.data.transferSize(52);
      //
      this.setData({
        initY:y
      });
      /* 
        item_id:this.data.item_id,
        visit_userid:,
        share_userid:this.data.userInfo_share.userid,
        phone:app.globalData.init_sale_phone||this.data.userInfo_share.corpUser.mobile,
        &page=${"page/shoppingMallMini/shoppingMallMini"}
        ${this.data.item_id}_${vuid}_${suid}_${phone}
      */
      //绘制标题 + 绘制二维码
      let vuid = app.globalData.visit_userid||this.data.userInfo_share.corpUser.userid||"";
      let suid = this.data.userInfo_share.userid;
      let phone = app.globalData.init_sale_phone||this.data.userInfo_share.corpUser.mobile;
      let qrcodeLink = `${this.data.Url}/getParamCode?appid=${app.globalData.accountInfo.miniProgram.appId}&page=${"pages/shoppingMallMini/shoppingMallMini"}&scene=${this.data.item_real_info.info.short_id}_${vuid}`;
      let qrs = this.data.transferSize(78);
      return this.data.paintImg.call(this,
        qrcodeLink,
        x1,
        y1,
        true,
        qrs,
        qrs
      ).then(info=>{
        let x2 = x1 + this.data.transferSize(0);
        let y2 = y1 + info.h + this.data.transferSize(26);
        let fs = this.data.transferSize(10);
        //
        return this.data.paintTxt.call(this, "· 长按识别二维码 ·", fs, x2, y2, 12, "#666");
      }).then(info=>{
        /* console.log(info);
        return this.data.paintImg.call(this,
          qrcodeLink,
          x1,
          y1,
          true,
          info.w,
          info.w
        ) */
      }).then(info=>{
        let fs = this.data.transferSize(22);
        return this.data.paintTxt.call(this, this.data.item_real_info.name, fs, x, y, 8, "#333");
      })
    }).then(info=>{
      let x = this.data.initX;
      let y = this.data.initY + this.data.transferSize(4) + this.data.transferSize(20);
      //
      this.setData({
        initY:y
      });
      let lw = this.data.transferSize(4);
      let x2 = x + this.data.transferSize(30);
      return this.data.paintLine.call(this,
        x,
        y,
        x2,
        y,
        lw,
        "#2D8CF0"
      );
    }).then(info=>{
      let x = this.data.initX;
      let y = this.data.initY + this.data.transferSize(14) + this.data.transferSize(16);
      //
      this.setData({
        initY:y
      });
      //
      let fs = this.data.transferSize(14);
      return this.data.paintTxt.call(this,`${this.data.item_real_info.describe[0]||'-'}`,fs, x, y, 16,"#666")
    }).then(info=>{
      let x = this.data.initX;
      let y = this.data.initY + this.data.transferSize(14) + this.data.transferSize(12);
      //
      this.setData({
        initY:y
      });
      //绘制标题
      let fs = this.data.transferSize(14);
      return this.data.paintTxt.call(this,`${this.data.item_real_info.describe[1]||'-'}`,fs, x, y, 16,"#666")
    }).then(()=>{
      //生成图片链接
      return this.data.getPosterImgUrl.call(this,'pro-canvas')
    }).then((src)=>{
      this.setData({
        posterImgSrc:src,
        showPosterPop: false
      });
      //
      wx.hideLoading();
    }).catch(err=>{
      //
      wx.hideLoading();
      //
      wx.showModal({
        title:"提示",
        content:`${err}`,
        showCancel:false
      })
    });
  },
  /* 关闭海报弹层 */
  closePosterPop(){
    this.setData({
      showPosterPop: true
    })
  },
  /* 打开分享弹层 */
  openSharePop(){
    if(!this.data.userInfo_share.mobile)return;
    this.setData({
      sharePop:true
    })
  },
  /* previewImages */
  showProductImgs:function(e){
    app.globalData.showProductImgs(e.currentTarget.dataset.info.image);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      options:options
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //获取canvas
    app.globalData.getCanvas.call(this,'pro-canvas')
    //
  },
  /* 获取用户手机号码 + 用户登录 */
  getPhoneNumber: function (e) {
    //console.log(e);
    return app.globalData.getPhoneNumber.call(this,e);
  },
  /* 获取用户信息 */
  getUserInfoFn: function (e) {
    //console.log(e);
    app.globalData.getUserInfoFn.call(this,e);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    try {
      //从分享进来(产品分享或者小程序二维码识别)  --  app.globalData.loginedFromProItem
      let scene = decodeURIComponent(this.data.options.scene);
      console.log(scene);
      if (typeof scene === 'string' && scene !== 'undefined') {
        //获取用户信息
        this.setData({
          userInfo_share: app.globalData.get_userInfo()
        });
        //
        let sceneArr = scene.split("_");
        console.log(sceneArr);
        //未登录
        if(!this.data.userInfo_share.mobile){
          let tmpObj = {};
          //产品分享
          if(sceneArr.length>2){
            tmpObj.scene = sceneArr[0];  //企业员工的userid
            tmpObj.share_userid = sceneArr[1]; //分享者的userid
            tmpObj.item_id = sceneArr[2];  //产品的item_id
            //存缓存
            wx.setStorageSync('product-share-notlogin', tmpObj);
            //存标记
            app.globalData.product_share_notlogin = true;
          }
          //小程序二维码识别
          if(sceneArr.length===2){
            tmpObj.short_id = sceneArr[0];  //产品的item_id(短号);
            tmpObj.scene = sceneArr[1];  //企业员工的userid
            //存缓存
            wx.setStorageSync('miniqrcode_distinguish_notlogin', tmpObj);
            //存标记
            app.globalData.miniqrcode_distinguish_notlogin = true;
          }
          //
          wx.showModal({
            content:`您暂未登录，请前往首页进行登录！`,
            showCancel:false,
            success:res=>{
              wx.switchTab({
                url: '/pages/index/index',
              })
            }
          });
        }
        //已登录
        if(this.data.userInfo_share.mobile){
          //产品分享
          if(sceneArr.length>2){
            this.setData({
              item_id:sceneArr[2]  //产品id
            });
            //首页刷新用
            wx.setStorageSync('first_open_corp_userid', sceneArr[0]);
            //订单用
            app.globalData.visit_userid = sceneArr[0];
            //
            this.getProductInfo({
              item_id:this.data.item_id,
              visit_userid:sceneArr[0]
            });
          }
          //小程序二维码识别
          if(sceneArr.length===2){
            this.setData({
              item_id:sceneArr[0]  //产品id
            });
            //首页刷新用
            wx.setStorageSync('first_open_corp_userid', sceneArr[1]);
            //订单用
            app.globalData.visit_userid = sceneArr[1];
            //
            this.getProductInfo({
              item_id:this.data.item_id,
              fnName:"getClassItemInfoForShortId",
              visit_userid:sceneArr[1]
            });
          }
        }
        //
        return;
      }
      //不从分享进入页面
      //用户信息
      this.setData({
        userInfo_share:app.globalData.get_userInfo()
      });
      //分享 + 从首页登录后跳转来
      //产品分享
      if(app.globalData.indexloginedToPSN){
        app.globalData.indexloginedToPSN = false;
        //
        let tmpObj = wx.getStorageSync('product-share-notlogin');
        //
        this.getProductInfo({
          item_id:tmpObj.item_id
        }).then(()=>{
          wx.removeStorage({
            key: 'product-share-notlogin',
          })
        })
      }
      //小程序二维码识别
      if(app.globalData.indexloginedToMDN){
        app.globalData.indexloginedToMDN = false;
        //
        let tmpObj = wx.getStorageSync('miniqrcode_distinguish_notlogin');
        //
        this.getProductInfo({
          item_id:tmpObj.short_id,
          fnName:"getClassItemInfoForShortId"
        }).then(()=>{
          wx.removeStorage({
            key: 'miniqrcode_distinguish_notlogin',
          })
        })
      }
      //从产品页跳转来
      if(app.globalData.fromProductPage){
        app.globalData.fromProductPage = false;
        //
        let eventChannel = this.getOpenerEventChannel();
        eventChannel.on('fromProductPage',data=>{
          //console.log(data);
          //
          this.setData({
            item_basic_info:data.info,
            item_id:data.info.item_id
          });
          //
          this.getProductInfo({
            item_id:data.info.item_id,
            visit_userid:app.globalData.visit_userid
          });
        });
      }
    } catch (error) {
      console.log(err)
    }
  },
  /* 获取产品信息 */
  getProductInfo({
    item_id = "",
    fnName="getClassItemInfo",
    visit_userid = "",
  }){
    //
    wx.showLoading({
      title: '获取产品详情',
      mask:true
    });
    //获取产品图片信息及保存用户访问记录
    return app.globalData[fnName].call(this,item_id).then(info=>{
      console.log(info);
      //简介信息
      info.describe = info.descibe?JSON.parse(info.descibe):[]
      //
      wx.setNavigationBarTitle({
        title: info.name,
      });
      //
      this.setData({
        item_real_info: info
      });
      //浏览员工信息记录
      return app.globalData.visitUser.call(this,{
        type:"1",
        userid: this.data.userInfo_share.userid, //
        visit_userid: visit_userid,  //
        type_id: info.item_id,
        type_value: info.name
      });
    }).then(()=>{
      wx.hideLoading();
    }).catch(err=>{
      wx.hideLoading();
      wx.showModal({
        title:'提示',
        content:`${err}`,
        showCancel:false
      })
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  /*  */
  onShareAppMessage(){
    //员工userid + 用户id + 产品id + 员工电话
    //登录之后
    if (app.globalData.visit_userid||this.data.userInfo_share.corpUser.userid) {
      let visit_userid = app.globalData.visit_userid||this.data.userInfo_share.corpUser.userid;
      return {
        title: `${this.data.item_real_info.name}`,
        path:`pages/shoppingMallMini/shoppingMallMini?scene=${visit_userid}_${this.data.userInfo_share.userid}_${this.data.item_id}`
      };
    }else{
      return false;
    }
  }
})